package com.pishou.code.csv;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.pishou.ParamConfig;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class CategoryCSV {

    private static String fileName = ParamConfig.file_path+"/category.csv";

    public static void setCategory(String[] list){
        if (list == null){
            return;
        }
        String  list_str = JSON.toJSONString(list);
        File file = createFile(fileName);

        try {
            FileWriter writer;
            writer = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(writer);
            bw.write("Category");
            bw.newLine();
            if(list!=null){
                bw.write(list_str.toString());
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String[] getCategory(){
        File file = createFile(fileName);
        String json_str="";
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8"));
            while (br.readLine()!=null) {
                json_str = br.readLine();
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<String> list =  new ArrayList<String>();
        if (json_str.length() > 0 ){
            list = JSONArray.parseArray(json_str,String.class);
            String[] array = new String[list.size()];
            for (int i=0;i<list.size();i++){
                array[i] = list.get(i);
            }
            return  array;
        }

        return new String[0];
    }

    public static File createFile(String fileNameTmp){
        File file = new File(fileNameTmp);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

}
